<template>
  <div>
    <div v-if="originData.length">
      已选{{ mapTypeName[type] }}: <Tag color="purple">{{ originData.length }}</Tag>
    </div>
    <div class="select-tag" v-if="originData.length">
      <!-- <Tag
        type="dot"
        :closable="typeDetail == true ? false : true"
        color="primary"
        @on-close="handleClose(content)"
        v-for="content in originData"
        :key="content.id"
        >{{ content.name || content.ccname || content.ecname || content.paperName }}</Tag
      > -->
      <Tag
        type="dot"
        :closable="typeDetail == true ? false : true"
        color="primary"
        @on-close="handleClose(content)"
        v-for="content in originData"
        :key="content.id"
        >{{ content.name }}</Tag
      >
    </div>
    <div class="formSearch mb15">
      <Checkbox v-model="mapType[type].params.isMe" class="gap" @on-change="queryList()"
        >由我创建</Checkbox
      >
      <Select filterable
        clearable
        placeholder="难度"
        class="gap select"
        v-model="mapType[type].params.difficulty"
        @on-change="queryList()"
      >
        <Option value="simple">简单</Option>
        <Option value="medium" v-if="type == 'testPaper'">中等</Option>
        <Option value="Medium" v-if="type != 'testPaper'">中等</Option>
        <Option value="hard">较难</Option>
      </Select>
      <Select filterable
        clearable
        v-if="type == 'experiment'"
        placeholder="课件模式"
        class="gap select"
        v-model="mapType[type].params.expType"
        @on-change="queryList()"
      >
        <Option value="0">实操课件</Option>
        <Option value="1">理论课件</Option>
        <Option value="2">文本课件</Option>
      </Select>
      <!-- <Select filterable
        clearable
        v-if="type == 'experiment'"
        placeholder="部署状态"
        class="gap select"
        v-model="mapType[type].params.deployStatus"
        @on-change="queryList()"
      >
        <Option value="10">未部署</Option>
        <Option value="3">部署成功</Option>
        <Option value="9">部署中</Option>
        <Option value="6">部署失败</Option>
      </Select> -->
      <Select filterable
        clearable
        v-if="(type == 'experiment' ||type == 'vedio') && (!code || code.length === 0)"
        placeholder="课件方向"
        class="gap select"
        clearable
        multiple
        filterable
        :max-tag-count="1"
        v-model="mapType[type].params.typeCode"
        @on-change="DqueryList()"
        style="width:260px"
      >
        <Option v-for="item in directionArr" :value="item.dictid" :key="item.dictid">{{
          item.dictname
        }}</Option>
      </Select>
      <Input
        v-model.trim="mapType[type].params.name"
        class="gap input"
        clearable
        placeholder="名称"
        @on-change="DqueryList()"
      />
    </div>
    <Table
      ref="selectTable"
      :columns="col"
      :data="data"
      @on-select="selectOneItem"
      @on-select-cancel="selectOneItemCancel"
      @on-select-all="selectAllItem"
      @on-select-all-cancel="selectAllItemCancel"
    >
      <template slot-scope="{ row }" slot="name">
        <a>{{ row.name }}</a>
      </template>
      <template slot-scope="{ row }" slot="action">
        <Button
          type="primary"
          :disabled="
            relativeIds.includes(row.id || row.ecid || row.ccid || row.paperId) ||
              row.isPublic == 0 || row.visibility == 'private' ||
              typeDetail == true || relativeIds.length >= 9
          "
          size="small"
          style="margin-right: 5px"
          @click="use(row)"
          >使用</Button
        >
        <Poptip confirm :transfer="true" title="确实要取消绑定关系吗?" @on-ok="cancel(row)">
          <Button
            type="error"
            size="small"
            :disabled="
              !relativeIds.includes(row.id || row.ecid || row.ccid || row.paperId) ||
                row.isPublic == 0 || row.visibility == 'private' ||
                typeDetail == true
            "
            >取消</Button
          >
        </Poptip>
      </template>
    </Table>
    <Page
      style="margin-top:15px;padding-bottom:10px"
      :total="total"
      :current="currentPage"
      show-total
      show-elevator
      @on-change="changePage"
      @on-page-size-change="changeSize"
    />
  </div>
</template>
<script>
import { addSkillPoint, querySkillPoint, delSkillPoint } from '@/api/selfStudy/skill.js';
import { getExpListNotPrivate, getcourselist } from '@/api/selfStudy/courseExp.js';
import { queryStudyVideo } from '@/api/videoSelfStudy.js';
import encryption from '@/libs/encryption.js';
import { queryTestPaperList } from '@/api/testpaper';
import commonFun from '@/mixin/common';
import { debounce, throttle } from '@/libs/utils';
export default {
  name: 'relativeList',
  props: ['type', 'code', 'id','directionArr','getType'],
  mixins: [commonFun],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      USER_ID: September.userId,
      USER_Name: September.nickname,
      col: [],
      data: [],
      relativeIds: [],
      relativeList: [],
      selectedContent: [],
      originData: [],
      originDataCopy: [],
      tempArr: [],
      currentPage: 1,
      current: {
        typeCode: '',
        id: ''
      },
      mapTypeName: {
        course: '课程',
        experiment: '课件',
        vedio: '视频',
        testPaper: '考试'
      },
      mapType: {
        //类型：0.课程、1.课件、2.视频、3.试卷、4.场景
        vedio: {
          //视频
          api: queryStudyVideo,
          col: [
            {
              type: 'selection',
              width: 60,
              align: 'center'
            },
            {
              title: '视频名称',
              key: 'name',
              tooltip: true
            },
            {
              title: '课件方向',
              key: 'typeCode',
              render: (h, params) => {
                return h('span', this.getType(params.row.typeCode) || '-');
              }
            },
            {
              title: '难度',
              key: 'difficulty',
              render: (h, params) => {
                return h('span', this.handlerDifficulty(params.row.difficulty));
              }
            },
            {
              title: '视频方向',
              key: 'typeCode',
              render: (h, params) => {
                return h('span', this.getType(params.row.typeCode) || '-');
              }
            },
            {
              title: '创建者',
              key: 'creatorName'
            },
            {
              title: '创建时间',
              key: 'createTime'
            },
            {
              title: '操作',
              slot: 'action',
              width: 150,
              align: 'center'
            }
          ],
          type: 2,
          params: {
            pageIndex: 1,
            pageSize: 10
          }
        },
        testPaper: {
          //试卷
          api: queryTestPaperList,
          type: 3,
          col: [
            {
              type: 'selection',
              width: 60,
              align: 'center'
            },
            {
              title: '试卷名称',
              key: 'paperName',
              tooltip: true
            },
            {
              title: '试卷难度',
              key: 'difficulty',
              render: (h, params) => {
                return h('span', this.handlerDifficulty(params.row.difficulty));
              }
            },
            {
              title: '分数',
              key: 'totalScore'
            },
            {
              title: '描述',
              key: 'description',
              tooltip: true
            },
            {
              title: '创建者',
              key: 'creatorName'
            },
            {
              title: '创建时间',
              key: 'created'
            },
            {
              title: '操作',
              slot: 'action',
              width: 150,
              align: 'center'
            }
          ],
          params: {
            pageIndex: 1,
            pageSize: 10
          },
          data: {
            //由于不同的接口用的是一个方法，试卷的接口和别的接口不一样，所以，这个配置是反的
          }
        },
        experiment: {
          //课件
          api: getExpListNotPrivate,
          type: 1,
          col: [
            {
              type: 'selection',
              width: 60,
              align: 'center'
            },
            {
              title: '课件名称',
              key: 'ecname',
              tooltip: true
            },
            {
              title: '课件模式',
              key: 'expType',
              render: (h, params) => {
                return h('span', this.handlerMode(params.row.expType));
              }
            },
            {
              title: '课件方向',
              key: 'typeCode',
              render: (h, params) => {
                return h('span', this.getType(params.row.typeCode) || '-');
              }
            },
            {
              title: '课件难度',
              key: 'difficulty',
              render: (h, params) => {
                return h('span', this.handlerDifficulty(params.row.difficulty));
              }
            },
            {
              title: '课件指导书',
              key: 'guidbookName',
              tooltip:true
            },
            {
              title: '课时',
              key: 'hours'
              // render:(h,params)=>{
              //   return h('span',params.row.hours+'小时')
              // }
            },
            {
              title: '操作',
              slot: 'action',
              width: 150,
              align: 'center'
            }
          ],
          params: {
            pageIndex: 1,
            pageSize: 10
          }
        },
        course: {
          //课程
          api: getcourselist,
          type: 0,
          col: [
            {
              type: 'selection',
              width: 60,
              align: 'center'
            },
            {
              title: '课程名称',
              key: 'ccname',
              tooltip: true
            },
            {
              title: '课件个数',
              render: (h, params) => {
                return h('span', params.row.expriments.length);
              }
            },
            {
              title: '课程难度',
              key: 'difficulty',
              render: (h, params) => {
                return h('span', this.handlerDifficulty(params.row.difficulty));
              }
            },
            {
              title: '课时',
              key: 'hours'
              // render:(h,params)=>{
              //   return h('span',params.row.hours+'小时')
              // }
            },
            {
              title: '操作',
              slot: 'action',
              width: 150,
              align: 'center'
            }
          ],
          params: {
            pageIndex: 1,
            pageSize: 10
          }
        }
      },
      typeDetail: '',
      total: 0
    };
  },
  methods: {
    selectOneItem(selection, row) {
      this.use(row);
    },
    selectOneItemCancel(selection, row) {
      this.cancel(row);
    },
    selectAllItem(selection) {
      this.use(selection);
    },
    selectAllItemCancel(selection) {
      this.cancel(this.data);
    },
    handleClose(item) {
      this.cancel(item,'tag');
    },
    queryRelative() {
      let params = {
        pageIndex: 1,
        pageSize: 9999,
        chapterId: this.current.id
      };
      return querySkillPoint(params)
        .then((res) => {
          if (res.code == 1) {
            this.relativeList = res.data.items;
            this.relativeIds = this.relativeList.map((item) => item.refId);
          } else {
            this.$Message.error(res.message);
          }
          return res;
        })
        .catch((e) => {
          return {};
        });
    },
    use(row) {
      let arr = [].concat(row);
      if(this.relativeIds.length + arr.length >= 10){
        this.init(
          this.type,
          this.current.typeCode,
          this.current.id,
          this.typeDetail,
          '',
          'needCopy'
        );
        this.$Message.warning('绑定个数超出上限');
        return;
      }
      let refs = arr.map((item) => {
        let refId = item.id || item.ecid || item.ccid || item.paperId;
        let type = this.mapType[this.type].type;
        return {
          refId,
          type
        };
      });
      let passObj = {
        careerSkillId: this.$route.query.id,
        chapterId: this.current.id,
        refs: refs
        // "refId": id,
        // "type": this.mapType[this.type].type
      };
      addSkillPoint(passObj).then((res) => {
        if (res.code == 1) {
          this.$Message.info('绑定成功');
          // this.queryRelative()
          this.init(
            this.type,
            this.current.typeCode,
            this.current.id,
            this.typeDetail,
            '',
            'needCopy'
          );
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    cancel(row,type) {
      const dels = [].concat(row);
      let delIds = [];
      if(type === 'tag'){
        delIds = dels.map((d) => d.id)
      }else{
        const ids = dels.map((d) => d.id || d.ecid || d.ccid || d.paperId);
        //const id = row.id||row.ecid||row.ccid||row.paperId
        const item = this.relativeList.filter((i) => ids.includes(i.refId));
        delIds = item.map((m) => m.id);
      }
      if (delIds.length) {
        delSkillPoint(delIds).then((res) => {
          if (res.code == 1) {
            this.$Message.info('取消绑定成功');
            // this.queryRelative()
            this.init(
              this.type,
              this.current.typeCode,
              this.current.id,
              this.typeDetail,
              '',
              'needCopy'
            );
          } else {
            this.$Message.error(res.message);
          }
        });
      } else {
        this.$Message.info('尚未绑定关系，无法取消');
      }
    },
    delItem(arr, key) {
      let index = arr.findIndex((item) => item.title == key);
      if (index != -1) {
        arr.splice(index, 1);
      }
    },
    async init(type, typeCode, id, showType, origin, originType) {
      let prePageIndex = this.mapType[type].params.pageIndex;
      let prePageSize = this.mapType[type].params.pageSize;
      this.current = {
        typeCode: typeCode,
        id: id
      };
      this.typeDetail = showType;
      let params = {...this.mapType[type].params};
      if (origin == 'tab') {
        params.pageIndex = 1;
        this.currentPage = params.pageIndex;
      }
      if (originType == 'needCopy'){ //绑定，取消绑定
        await this.queryRelative();
      }
      // const res = await this.queryRelative();
      // if (res.code == 1) {
      //   this.relativeIds = res.data.items.map((item) => item.refId);
      // }
      this.col = [...this.mapType[type].col];
      // if (showType == 'detail') { //查询一次
      //   // this.delItem(this.col,'操作');
      //   params.pageIndex = 1;
      //   params.pageSize = 9999;
      // }
      let p = { ...this.mapType[type].params };
      let d = { ...this.mapType[type].data };
      // 0.课程、1.课件、2.视频、3.试卷
      if (type !== 'testPaper') {
        //非考试
        // this.mapType[type].params.typeCode = this.current.typeCode;
        // p.typeCode = this.current.typeCode;
        if (this.type == 'experiment') {
          p.ecname = p.name;
          p.isown = this.mapType[type].params.isMe ? true : undefined;
          p.typeCodeList = typeCode ? typeCode.split(',') : this.mapType[type].params.typeCode
          delete p.name;
          delete p.typeCode
          this.originData = this.relativeList.filter(item => item.type === 1)
        } else if (this.type == 'course') {
          p.typeCode = ''; //课程不使用这个字段了
          p.ccname = p.name;
          delete p.name;
          p.createUserID = this.mapType[type].params.isMe ? this.USER_ID : undefined;
          this.originData = this.relativeList.filter(item => item.type === 0)
        } else if (this.type == 'vedio') {
          p.creator = this.mapType[type].params.isMe ? this.USER_ID : undefined;
          this.originData = this.relativeList.filter(item => item.type === 2)
        }
        delete p.isMe;
      } else {
        //考试
        let { pageIndex, pageSize, ...rest } = this.mapType[type].params;
        d = { pageIndex, pageSize };
        p = { ...rest };
        p.paperName = p.name;
        p.queryType = 'xl';
        p.paperType = 'paper_fixed',
        p.self = this.mapType[type].params.isMe ? 1 : undefined;
        //p.questionType='no_env_no_flag'
        delete p.name;
        delete p.isMe;
        this.originData = this.relativeList.filter(item => item.type === 3)
      }
      this.mapType[type].api(p, d).then((res) => {
        let r = res.code || res.data.code;
        if (r == 1) {
          let datas = res.items || res.data.items || res.data.data.list;
          if (type == 'testPaper') {
            datas = datas.filter((d) => d.questionType != 'no_env_no_flag' && !d.advanced);
          }
          datas.forEach((item) => {
            item._checked = false;
          });
          if (origin == 'tab') {
            this.tempArr = JSON.parse(JSON.stringify(datas));
          }
          datas.forEach((d) => {
            let flag = this.relativeIds.includes(d.id || d.ecid || d.ccid || d.paperId);
            if (flag) {
              d._checked = true;
            }
            if (this.typeDetail == true || d.isPublic == 0 || d.visibility == 'private') {
              d._disabled = true;
            }
          });
          // if (originType == 'needCopy') {
          //   this.originData = this.tempArr.filter((d) => {
          //     let flag = this.relativeIds.includes(d.id || d.ecid || d.ccid || d.paperId);
          //     if (flag) {
          //       d._checked = true;
          //     }
          //     if (this.typeDetail == true || d.isPublic == 0 || d.visibility == 'private') {
          //       d._disabled = true;
          //     }
          //     return flag;
          //   });
          //   // this.originDataCopy = JSON.parse(JSON.stringify(this.originData));
          // }
          this.mapType[type].params.pageIndex = prePageIndex;
          this.mapType[type].params.pageSize = prePageSize;
          this.data = datas;//this.fontPaging(datas, this.mapType[type].params);
          if(this.relativeIds.length >=9){
            this.data.forEach(item => {
              if(!item._checked){
                item._disabled = true
              }
            })
          }
          this.total = res.total || res.data.total; //datas.length;
        }
      });
    },
    handlerVisible(v) {
      const mapVisible = {
        share: '单位',
        private: '个人'
      };
      return mapVisible[v];
    },
    handlerDifficulty(d) {
      d = d.toLowerCase();
      const mapDiff = {
        simple: '简单',
        medium: '中等',
        hard: '较难'
      };
      return mapDiff[d];
    },
    handlerFileType(type) {
      const mapType = {
        images: '图片',
        videos: '视频',
        docs: '文档',
        audios: '音频',
        relay: 'relay',
        toolkit: '工具',
        icon: '图标',
        files: '其他'
      };
      return mapType[type] ? mapType[type] : '其他';
    },
    handlerMode(mode) {
      const mapMode = {
        0: '实操课件',
        1: '理论课件',
        2: '文本课件'
      };
      return mapMode[mode];
    },
    changePage(page) {
      this.currentPage = page;
      this.mapType[this.type].params.pageIndex = page;
      this.init(this.type, this.current.typeCode, this.current.id, this.typeDetail);
    },
    changeSize(size) {
      this.mapType[this.type].params.pageSize = size;
      this.init(this.type, this.current.typeCode, this.current.id, this.typeDetail);
    },
    queryList(type) {
      this.currentPage = 1;
      this.mapType[this.type].params.pageIndex = 1;
      this.init(this.type, this.current.typeCode, this.current.id, this.typeDetail, type);
    },
    initSearch(name) {
      this.mapType[name].params = {
        pageIndex: 1,
        pageSize: 10
      };
      this.$nextTick(() => {
        this.$set(this.mapType[name].params, 'isMe', false);
        this.$set(this.mapType[name].params, 'difficulty', undefined);
        this.$set(this.mapType[name].params, 'expType', undefined);
        this.$set(this.mapType[name].params, 'deployStatus', undefined);
        this.$set(this.mapType[name].params, 'name', '');
      });
    },
    DqueryList: debounce(function() {
      this.queryList();
    }, 500)
  },
  async mounted() {
    //console.log(this.type)
    //this.init(this.type)
  }
};
</script>
<style scoped src="./skill.css"></style>
<style scoped>
.select-tag {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  margin: 16px 0;
}
.pageWrap {
  height: calc(100vh - 60px);
}
</style>
